package com.shanghaionstar.discover.charge.presenter;

import android.util.Log;

import com.google.gson.Gson;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.framework.mvp.base.IMVPScheduler;
import com.onstar.cn.framework.mvp.base.IMVPView;
import com.onstar.cn.framework.mvp.base.core.BaseActivity;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.framework.utils.RxBus;
import com.onstar.cn.mag.CommuteScheduleEntity;
import com.onstar.cn.mag.Week;
import com.onstar.cn.mag.enumtype.RemoteCommandsType;
import com.onstar.cn.rxconstants.RxConstants;
import com.onstar.cn.vehicle.entity.RequestStatus;
import com.onstar.cn.vehicle.result.PollingResult;
import com.onstar.cn.weight.ToastView;
import com.shanghaionstar.R;
import com.shanghaionstar.discover.charge.iview.IChargeModeTimeView;
import com.shanghaionstar.discover.charge.model.ChargeModeTimeItem;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.remote.model.RemoteModel;
import com.shanghaionstar.remote.service.RemoteService;
import com.shanghaionstar.report.bean.ReportReqParam;
import com.shanghaionstar.utils.BusinessUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import rx.Subscription;
import rx.functions.Action1;
import rx.functions.Func1;

/**
 * Created by 7828wc on 16/7/21.
 */
public class ChargeModeTimePresenter extends BasePresenter<Class<?>> {
    private String[] weekDay = {"SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"};
    private IChargeModeTimeView view;
    private BaseActivity mContext;

    private RemoteService remoteCommandUtil;
    private Subscription pollingSubscription;
    private CommuteScheduleEntity commuteScheduleEntity;
    boolean isMinuteScroll;
    boolean isHourScroll;

    private List<ChargeModeTimeItem> list;

    public ChargeModeTimePresenter(IMVPScheduler mvpScheduler) {
        super(mvpScheduler);
        registerPollingSub();
    }

    @Override
    public void setView(IMVPView<Class<?>> view) {
        super.setView(view);
        this.view = (IChargeModeTimeView) view;
        mContext = (BaseActivity) view.onActivity();
    }

    public void initList() {
        list = new ArrayList<ChargeModeTimeItem>(7);
        list.add(0, new ChargeModeTimeItem(mContext.getString(R.string.sunday), "00", "00", false));
        list.add(1, new ChargeModeTimeItem(mContext.getString(R.string.monday), "00", "00", false));
        list.add(2, new ChargeModeTimeItem(mContext.getString(R.string.tuesday), "00", "00", false));
        list.add(3, new ChargeModeTimeItem(mContext.getString(R.string.wednesday), "00", "00", false));
        list.add(4, new ChargeModeTimeItem(mContext.getString(R.string.thursday), "00", "00", false));
        list.add(5, new ChargeModeTimeItem(mContext.getString(R.string.friday), "00", "00", false));
        list.add(6, new ChargeModeTimeItem(mContext.getString(R.string.saturday), "00", "00", false));
        view.setAdapter(list);
        remoteCommandUtil = new RemoteService(mContext);
    }

    public int[] onItemClick(int position) {
        int retractPosition = -1, collapsePosition = -1;
        for (int i = 0; i < list.size(); i++) {
            ChargeModeTimeItem item = list.get(i);
            boolean oldSelected = item.selected;
            if (i == position) {
                item.selected = !item.selected;
            } else {
                item.selected = false;
            }
            boolean freshSelected = item.selected;
            if (freshSelected != oldSelected) {
                if (freshSelected) {
                    collapsePosition = i;
                } else {
                    retractPosition = i;
                }
            }
        }
        int[] p = new int[2];
        p[0] = retractPosition;
        p[1] = collapsePosition;
        return p;
    }

    public void requestSchedule() {
        RemoteModel remoteModel = new RemoteModel.Builder().setRemoteCommandsType(RemoteCommandsType.COMMAND_GETCOMMUTESCHEDULE).create();
        requestChargeMode(remoteModel);
    }

    public void requestChargeMode(RemoteModel remoteModel) {
        view.setLoading(true);
        subscription = remoteCommandUtil.commandByType(remoteModel)
                .subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {

                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        //里面抛出的Error信息
                        if (view != null)
                            view.onResponseError((OnStarException) throwable);
                    }
                });
    }

    /**
     * 处理Polling 返回结果
     */
    private void registerPollingSub() {
        pollingSubscription = RxBus.getDefault()
                .toObserverable(RxConstants.ALL_PAGE_ALERT, PollingResult.class).filter(new Func1<PollingResult, Boolean>() {
                    @Override
                    public Boolean call(PollingResult pollingResult) {
                        return pollingResult.getRequestType().equalsIgnoreCase(RemoteCommandsType.COMMAND_GETCOMMUTESCHEDULE.value())
                                || pollingResult.getRequestType().equalsIgnoreCase(RemoteCommandsType.COMMAND_SETCOMMUTESCHEDULE.value());
                    }
                })
                .subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread())
                .subscribe(new Action1<PollingResult>() {
                    @Override
                    public void call(PollingResult pollingResult) {
//                        if (RequestStatus.Success.getStringValue().equalsIgnoreCase(pollingResult.getRequestStatus())) {
                        updateView(pollingResult);
//                        }
                    }
                });
    }


    public void onSave() {
        view.setLoading(true);
        BusinessUtil.sendReportByClickType(mContext, FunctionNameFindId.PhevSaveTime.getStringValue());
        CommuteScheduleEntity entity = new CommuteScheduleEntity();
        CommuteScheduleEntity.WeekCommuteSchedule weeklyCommuteSchedule = new CommuteScheduleEntity.WeekCommuteSchedule();
        if (list != null) {
            int N = list.size();
            List<CommuteScheduleEntity.DailyCommuteSchedule> schedules = new ArrayList<CommuteScheduleEntity.DailyCommuteSchedule>();
            for (int i = 0; i < N; i++) {
                CommuteScheduleEntity.DailyCommuteSchedule schedule = new CommuteScheduleEntity.DailyCommuteSchedule();
                schedule.setDayOfWeek(weekDay[i]);
                String departTime = list.get(i).hour + ":" + list.get(i).minute + ":00";
                schedule.setDepartTime(departTime);
                schedules.add(schedule);
            }
            weeklyCommuteSchedule.setDailyCommuteSchedule(schedules);
        }
        entity.setWeeklyCommuteSchedule(weeklyCommuteSchedule);
        String jsonBody = new Gson().toJson(entity);
        RemoteModel model = new RemoteModel.Builder()
                .setRemoteCommandsType(RemoteCommandsType.COMMAND_SETCOMMUTESCHEDULE)
                .setBody(jsonBody)
                .create();
        requestChargeMode(model);
    }

//    private Handler handler = new Handler() {
//        @Override
//        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
//            switch (msg.what) {
//                case Constants.SERVICE_RESPONSE_FAILURE:
//                case Constants.SERVICE_RESPONSE_ERROR:
//                    ErrorInfo errorInfo = (ErrorInfo) msg.getData().getSerializable("errorInfo");
//                    String errorMsg = ErrorCodeUtil.getErrorMsgByCode(parent, errorInfo);
//                    AlertDialogUtil.showAlertDialog(parent, getString(R.string.dialog_warning), errorMsg);
//                    dismissProgress();
//                    break;
//                case Constants.SERVICE_HTTP_ERROR:
//                    HttpException e = (HttpException) msg.getData().getSerializable("HttpException");
//                    AlertDialogUtil.showDialogByExceptionCode(parent, e);
//                    dismissProgress();
//                    break;
//                case Constants.SERVICE_RESPONSE_INPROGRESS:
//                    break;
//                default:
//                    break;
//            }
//        }
//    };

    public void updateView(PollingResult result) {
        view.setLoading(false);
        // String testjson =
        // "{\"commandResponse\":{\"requestTime\":\"2016-01-21T03:11:10.771Z\",\"completionTime\":\"2016-01-21T03:11:27.052Z\",\"url\":\"https://api.gm.com/api/v1/account/vehicles/LSGKR5WL9GA000276/requests/971416\",\"status\":\"success\",\"type\":\"getCommuteSchedule\",\"body\":{\"weeklyCommuteSchedule\":{\"dailyCommuteSchedule\":[{\"dayOfWeek\":\"FRI\",\"departTime\":\"10:00:00\"},{\"dayOfWeek\":\"MON\",\"departTime\":\"07:00:00\"},{\"dayOfWeek\":\"SAT\",\"departTime\":\"07:00:00\"},{\"dayOfWeek\":\"SUN\",\"departTime\":\"07:00:00\"},{\"dayOfWeek\":\"THU\",\"departTime\":\"10:45:00\"},{\"dayOfWeek\":\"TUE\",\"departTime\":\"07:45:00\"},{\"dayOfWeek\":\"WED\",\"departTime\":\"08:00:00\"}]}}}}";
        // result.setRequestStatus(RequestStatus.Success.getStringValue());
        // result.setRequestType(RemoteCommandsType.COMMAND_GETCOMMUTESCHEDULE.value());
        // result.setJson(testjson);
        if (RemoteCommandsType.COMMAND_GETCOMMUTESCHEDULE.value().equals(result.getRequestType())) {
            if (result.getRequestStatus().equals(RequestStatus.Success.getStringValue())) {
                BusinessUtil.sendReportByRequestParams(mContext, FunctionNameFindId.PhevTime_Get.getStringValue(), ReportReqParam.getChargeTimeReqParm(true));
                try {
                    String json = result.getJson();
                    JSONObject jsonObject = new JSONObject(json);
                    JSONObject bodyObject = jsonObject.getJSONObject("commandResponse").getJSONObject("body");
//					JSONObject scheduleObject = bodyObject.getJSONObject("weeklyCommuteSchedule");
                    commuteScheduleEntity = new Gson().fromJson(bodyObject.toString(), CommuteScheduleEntity.class);
//							(,bodyObject.toString());
                    fillListByEntity(commuteScheduleEntity);
                    view.notifyDataChange();
                    Log.e("zk", "entity=" + commuteScheduleEntity);
                } catch (JSONException e) {
                    e.printStackTrace();
//					Toast.makeText(parent, "analyze json failure", Toast.LENGTH_SHORT).show();
                }
            } else {
                if (result.getRequestStatus().equals(RequestStatus.Failure.getStringValue())) {
                    String msg = result.getErrorInfo()==null?"":result.getErrorInfo().getMsg();
                    BusinessUtil.sendReportByRequestParams(mContext, FunctionNameFindId.PhevTime_Get.getStringValue(), ReportReqParam.getChargeTimeReqParm(false,msg));
                    ToastView toast = new ToastView(mContext);
                    toast.showToast(mContext.getString(R.string.departure_time_retrieving_failed));
//					Toast.makeText(parent, "network failure", Toast.LENGTH_SHORT).show();
                }
            }
        } else if (RemoteCommandsType.COMMAND_SETCOMMUTESCHEDULE.value().equals(result.getRequestType())) {
            if (result.getRequestStatus().equals(RequestStatus.Success.getStringValue())) {
                BusinessUtil.sendReportByRequestParams(mContext, FunctionNameFindId.PhevSaveTime.getStringValue(), ReportReqParam.getSetChargeTimeReqParm(true));
                ToastView toast = new ToastView(mContext);
                toast.showToast(mContext.getString(R.string.departure_time_upadte_success));
                view.mBack();
            } else {
                String msg = result.getErrorInfo()==null?"":result.getErrorInfo().getMsg();
                BusinessUtil.sendReportByRequestParams(mContext, FunctionNameFindId.PhevSaveTime.getStringValue(), ReportReqParam.getSetChargeTimeReqParm(false,msg));
                ToastView toast = new ToastView(mContext);
                toast.showToast(mContext.getString(R.string.departure_time_upadte_failed));
            }
        }

    }

    private void fillListByEntity(CommuteScheduleEntity commuteScheduleEntity) {
        List<CommuteScheduleEntity.DailyCommuteSchedule> dailyCommuteSchedules = commuteScheduleEntity.getWeeklyCommuteSchedule()
                .getDailyCommuteSchedule();
        if (dailyCommuteSchedules != null && dailyCommuteSchedules.size() > 0) {
            for (CommuteScheduleEntity.DailyCommuteSchedule dailyCommuteSchedule : dailyCommuteSchedules) {
                Week week = Week.fromValue(dailyCommuteSchedule.getDayOfWeek());
                if (week == null) return;
                String[] departTime = dailyCommuteSchedule.getDepartTime().split(":");
                switch (week) {
                    case SUN:
                        list.set(0, new ChargeModeTimeItem(mContext.getString(R.string.sunday), departTime[0], departTime[1], false));
                        break;
                    case MON:
                        list.set(1,
                                new ChargeModeTimeItem(mContext.getString(R.string.monday), departTime[0], departTime[1], false));
                        break;
                    case TUE:
                        list.set(2,
                                new ChargeModeTimeItem(mContext.getString(R.string.tuesday), departTime[0], departTime[1], false));
                        break;
                    case WED:
                        list.set(3,
                                new ChargeModeTimeItem(mContext.getString(R.string.wednesday), departTime[0], departTime[1], false));
                        break;
                    case THU:
                        list.set(4,
                                new ChargeModeTimeItem(mContext.getString(R.string.thursday), departTime[0], departTime[1], false));
                        break;
                    case FRI:
                        list.set(5,
                                new ChargeModeTimeItem(mContext.getString(R.string.friday), departTime[0], departTime[1], false));
                        break;
                    case SAT:
                        list.set(6,
                                new ChargeModeTimeItem(mContext.getString(R.string.saturday), departTime[0], departTime[1], false));
                        break;
                }
            }
        }
    }

    public void finish() {
        super.finish();
        if (pollingSubscription != null && !pollingSubscription.isUnsubscribed()) {
            pollingSubscription.unsubscribe();
            pollingSubscription = null;
        }
    }

}
